package com.example.config;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Aspect
@Slf4j
@Component
public class WebLogAspect {
    @Pointcut("@within(org.springframework.stereotype.Controller) || " +
            " @within(org.springframework.web.bind.annotation.RestController)")
    public void cutController() {}

    @Around("cutController()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取拦截方法的参数
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        List<Object> list = Lists.newArrayList();
        for (Object object : joinPoint.getArgs()) {
            if (object instanceof MultipartFile || object instanceof HttpServletRequest
                    || object instanceof HttpServletResponse || object instanceof BindingResult) {
                continue;
            }
            list.add(object);
        }
        String uuid = IdUtil.simpleUUID();
        log.info("[{}]请求url[{}]开始,请求参数[{}]", uuid, url, StrUtil.join(",", list));
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis() - start;
        log.info("[{}]请求url[{}]结束,耗时[{}]毫秒,响应结果[{}]", uuid, url, end, result);
        return result;
    }
}
